/*
 * @Description: 实名认证   RealNameAuthentication
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-08-27 11:38:31
 * @LastAuthor   : zhengzhuang
 * @lastTime     : 2020-01-09 13:32:34
 */
import 'package:city_pickers/city_pickers.dart' as prefix;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/JhPickerTool.dart';
import 'package:C20Driver/utils/MyDialog.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:C20Driver/widget/rain_cell.dart';
import 'package:C20Driver/widget/spinkit.dart';
import 'package:async/async.dart';

class RealNameAuthentication extends StatefulWidget {
  @override
  _RealNameAuthenticationState createState() => _RealNameAuthenticationState();
}

class _RealNameAuthenticationState extends State<RealNameAuthentication> {
  final AsyncMemoizer _memoizer = AsyncMemoizer();
  int _isAgree; //是否重新填写信息
//  String _name; // 银行卡姓名
  String _nameAccount; // 银行卡姓名
//  String _iDNumber; // 身份证号
  String _iDNumberAccount; // 身份证号
//  String _accountNo; // 银行卡账号
  String _accountNoAccount; // 银行卡账号
//  String _bankLeaveMobile; // 银行预留手机号
  String _bankLeaveMobileFill; // 银行预留手机号填写
  String _regionVice = '请选择开户地区'; // 开户地区
  String _openBankNameVice = '请选择银行'; // 开户银行
  String _bankId; // 开户银行简称
  List<String> _bank = [];
  List _bankList = [];

  @override
  void initState() {
    super.initState();
    _getSupportBankList();
  }

  Future _getUserBankCard() async {
    return _memoizer.runOnce(() async {
      var dataInfo = await Request.getUserBankCard();
      print('dataInfo：==============$dataInfo');
      if (mounted) {
        setState(() {
//          提现信息完善状态 0:未认证（可全部修改） 1:已认证 2:重新认证（可全部修改）3:部分认证（只可修改身份证号）
          // _isAgree = 0;
          _isAgree = dataInfo['is_agree'];
          _nameAccount = dataInfo['account_name'];
          _accountNoAccount = dataInfo['account_no_raw'];
          _iDNumberAccount = dataInfo['crp_id_no_raw'];
          _bankLeaveMobileFill = dataInfo['bank_reserved_mobile'];
          _regionVice = dataInfo['regist_address'];
          _openBankNameVice = dataInfo['open_bank_name'];
        });
      }
      return dataInfo;
    });
  }

  /// 选择开户地区
  _selectCity() async {
    prefix.Result result = await prefix.CityPickers.showCityPicker(
      context: context,
    );
    if (result == null) return;
    setState(() {
      _regionVice = result.provinceName + result.cityName + result.areaName;
    });
  }

  /// 选择开户银行
  _selectBank() async {
    JhPickerTool.showStringPicker(context, data: _bank,
        clickCallBack: (int index, var str) {
      setState(() {
        _openBankNameVice = str;
      });
      for (var i = 0; i < _bankList.length; i++) {
        if (_bankList[i]['bank_name'] == _openBankNameVice) {
          setState(() {
            _bankId = _bankList[i]['bank_id'];
          });
        }
      }
    });
  }

  /// 获取开户银行
  void _getSupportBankList() async {
    List dataInfo = await Request.getSupportBankList();
    for (var i = 0; i < dataInfo.length; i++) {
      _bank.add(dataInfo[i]['bank_name']);
    }
    setState(() {
      _bank = _bank;
      _bankList = dataInfo;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('添加银行卡'),
        centerTitle: true,
        elevation: 0,
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          width: double.infinity,
          height: double.infinity,
          color: Color(0xffffffff),
          child: FutureBuilder(
              future: _getUserBankCard(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                print('dataInfo：==============$_isAgree');
                if (snapshot.hasData) {
                  // 0:未认证（可全部修改） 1:已认证 2:重新认证（可全部修改）3:部分认证（只可修改身份证号）
                  //提现信息完善状态 0:未认证（可全部修改） 1:已认证 2:重新认证（可全部修改）3:部分认证（只可修改身份证号）
                  if (_isAgree == 0) {
                    return _isAgreeZero();
                  } else if (_isAgree == 1) {
                    return _isAgreeOne();
                  } else if (_isAgree == 2) {
                    return _isAgreeZero();
                  } else if (_isAgree == 3) {
                    return _isAgreeThree();
                  } else {
                    return Container();
                  }
                } else {
                  return Spinkit();
                }
              }),
        ),
      ),
    );
  }

  _submitCertificatesInfo() {
    if (_nameAccount == null) return ToastX.center('请输入银行卡用户人姓名');
    if (_iDNumberAccount == null) return ToastX.center('请输入身份证号码');
    if (_isCardNo(_iDNumberAccount) == false)
      return ToastX.center('请输入正确身份证号码');
    if (_accountNoAccount == null) return ToastX.center('请输入银行卡账号');
    if (_bankLeaveMobileFill == null) return ToastX.center('请输入银行卡预留手机号');
    if (_openBankNameVice == '请选择银行' || _openBankNameVice == '')
      return ToastX.center('请选择银行');

    Request.bindBankCard(
      context,
      _nameAccount,
      _accountNoAccount,
      _bankLeaveMobileFill,
      _regionVice,
      _openBankNameVice,
      _iDNumberAccount,
    );
  }

  bool _isCardNo(String cardNo) {
    RegExp exp = RegExp(
        r'(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)');
    var boolmatched = exp.hasMatch(cardNo);
    return boolmatched;
  }

  Widget _isAgreeZero() {
    return Container(
      child: ListView(
        padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(30.0),
          right: ScreenUtil().setWidth(30.0),
        ),
        children: <Widget>[
          SizedBox(height: ScreenUtil().setWidth(30.0)),
          Text(
            '银行卡信息',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: ScreenUtil().setWidth(28),
                fontWeight: FontWeight.w400),
          ),
          SizedBox(height: ScreenUtil().setWidth(30.0)),
          caiTypeView(),
          BackCarCell(
            title: "所属银行",
            des: _openBankNameVice == '' ? '请选择银行' : _openBankNameVice,
            enabled: true,
            click: _selectBank,
          ),
          BackCarCell(
            title: "银行卡号",
            des: "请输入银行卡号",
            onChanged: (res) {
              setState(() {
                _accountNoAccount = res;
              });
            },
          ),
          SizedBox(height: ScreenUtil().setWidth(56.0)),
          Text(
            '银行卡信息',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: ScreenUtil().setWidth(28),
                fontWeight: FontWeight.w400),
          ),
          SizedBox(height: ScreenUtil().setWidth(36.0)),
          BackCarCell(
            title: "持卡人",
            des: "请输入持卡人",
            onChanged: (res) {
              setState(() {
                _nameAccount = res;
              });
            },
          ),
          BackCarCell(
              title: "身份证号",
              des: "请输入身份证号",
              onChanged: (res) {
                setState(() {
                  _iDNumberAccount = res;
                });
              }),
          BackCarCell(
              title: "银行预留手机号",
              des: "请输入手机号码",
              onChanged: (res) {
                setState(() {
                  _bankLeaveMobileFill = res;
                });
              }),
          SizedBox(height: ScreenUtil().setWidth(56.0)),
          InkWell(
            child: Container(
              alignment: Alignment.center,
              width: ScreenUtil().setWidth(686),
              height: ScreenUtil().setWidth(98),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Color(0xff3FB956),
                    Color(0xff65CA00),
                  ],
                ),
                borderRadius: BorderRadius.all(
                  Radius.circular(ScreenUtil().setWidth(49)),
                ),
              ),
              child: Text(
                '添加银行卡',
                style: TextStyle(
                  color: Color(0xffffffff),
                  fontSize: ScreenUtil().setSp(32),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            onTap: () {
              _submitCertificatesInfo();
            },
          ),
          SizedBox(height: ScreenUtil().setWidth(44.0)),
        ],
      ),
    );
  }

  Widget _isAgreeOne() {
    return Container(
      child: ListView(
        padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(30.0),
          right: ScreenUtil().setWidth(30.0),
        ),
        children: <Widget>[
          SizedBox(height: ScreenUtil().setWidth(30.0)),
          Text(
            '银行卡信息',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: ScreenUtil().setWidth(28),
                fontWeight: FontWeight.w400),
          ),
          SizedBox(height: ScreenUtil().setWidth(30.0)),
          caiTypeView(),
          BackCarCell(title: "所属银行", des: "$_openBankNameVice", enabled: false),
          BackCarCell(title: "银行卡号", des: "$_accountNoAccount", enabled: false),
          SizedBox(height: ScreenUtil().setWidth(56.0)),
          Text(
            '持卡人信息',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: ScreenUtil().setWidth(28),
                fontWeight: FontWeight.w400),
          ),
          SizedBox(height: ScreenUtil().setWidth(36.0)),
          BackCarCell(title: "持卡人", des: "$_nameAccount", enabled: false),
          BackCarCell(title: "身份证号", des: "$_iDNumberAccount", enabled: false),
          BackCarCell(
              title: "银行预留手机号", des: "$_bankLeaveMobileFill", enabled: false),
          SizedBox(height: ScreenUtil().setWidth(56.0)),
        ],
      ),
    );
  }

  Widget _isAgreeTwo() {
    return Container(
      child: ListView(
        padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(30.0),
          right: ScreenUtil().setWidth(30.0),
        ),
        children: <Widget>[
          SizedBox(height: ScreenUtil().setWidth(30.0)),
          RainCell(
              title: "账户姓名",
              des: this._nameAccount == null ? "" : this._nameAccount,
              onChanged: (res) {
                setState(() {
                  _nameAccount = res;
                });
              }),
          RainCell(
              title: "身份证号",
              des: this._iDNumberAccount == null ? "" : this._iDNumberAccount,
              onChanged: (res) {
                setState(() {
                  _iDNumberAccount = res;
                });
              }),
          RainCell(
              title: "银行卡账号",
              des: this._accountNoAccount == null ? "" : this._accountNoAccount,
              onChanged: (res) {
                setState(() {
                  _accountNoAccount = res;
                });
              }),
          RainCell(
              title: "预留手机号",
              des: this._bankLeaveMobileFill == null
                  ? ""
                  : this._bankLeaveMobileFill,
              onChanged: (res) {
                setState(() {
                  _bankLeaveMobileFill = res;
                });
              }),
          RainCell(
              title: "开户地区",
              des: this._regionVice == null ? "请选择开户地区" : this._regionVice,
              enabled: true,
              click: _selectCity),
          RainCell(
              title: "开户银行",
              des: this._openBankNameVice == null
                  ? "请选择银行"
                  : this._openBankNameVice,
              enabled: true,
              click: _selectBank),
          SizedBox(height: ScreenUtil().setWidth(32.0)),
          MaterialButton(
            color: Color.fromARGB(255, 255, 153, 0),
            disabledColor: Color.fromARGB(255, 188, 188, 188),
            minWidth: ScreenUtil().setWidth(700.0),
            height: ScreenUtil().setWidth(100.0),
            textColor: Colors.white,
            child: Text(
              '提交',
              style: TextStyle(
                fontSize: ScreenUtil().setSp(35.0),
              ),
            ),
            onPressed: () => _submitCertificatesInfo(),
          ),
          SizedBox(height: ScreenUtil().setWidth(26.0)),
          Text(
            '1.请确认信息无误后提交。(验证通过后不可修改，如有问题请在工作日08：30～18：00拨打客服电话 400-089-3089)',
            style: TextStyle(
              fontSize: ScreenUtil().setSp(26.0),
              color: Colors.black54,
            ),
          ),
          SizedBox(height: ScreenUtil().setWidth(10.0)),
          Text(
            '2.每日最多提交三次。',
            style: TextStyle(
              fontSize: ScreenUtil().setSp(26.0),
              color: Colors.black54,
            ),
          ),
          SizedBox(height: ScreenUtil().setWidth(80.0))
        ],
      ),
    );
  }

  Widget _isAgreeThree() {
    return Container(
      child: ListView(
        padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(30.0),
          right: ScreenUtil().setWidth(30.0),
        ),
        children: <Widget>[
          SizedBox(height: ScreenUtil().setWidth(30.0)),
          Text(
            '银行卡信息',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: ScreenUtil().setWidth(28),
                fontWeight: FontWeight.w400),
          ),
          SizedBox(height: ScreenUtil().setWidth(30.0)),
          caiTypeView(),
          BackCarCell(title: "所属银行", des: "$_openBankNameVice", enabled: false),
          BackCarCell(title: "银行卡号", des: "$_accountNoAccount", enabled: false),
          SizedBox(height: ScreenUtil().setWidth(56.0)),
          Text(
            '持卡人信息',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: ScreenUtil().setWidth(28),
                fontWeight: FontWeight.w400),
          ),
          SizedBox(height: ScreenUtil().setWidth(36.0)),
          BackCarCell(title: "持卡人", des: "$_nameAccount", enabled: false),
          BackCarCell(
            title: "身份证号",
            des: this._iDNumberAccount == null ? "" : this._iDNumberAccount,
            onChanged: (res) {
              setState(() {
                _iDNumberAccount = res;
              });
            },
          ),
          BackCarCell(
              title: "银行预留手机号", des: "$_bankLeaveMobileFill", enabled: false),
          SizedBox(height: ScreenUtil().setWidth(56.0)),
          InkWell(
            child: Container(
              alignment: Alignment.center,
              width: ScreenUtil().setWidth(686),
              height: ScreenUtil().setWidth(98),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Color(0xff3FB956),
                    Color(0xff65CA00),
                  ],
                ),
                borderRadius: BorderRadius.all(
                  Radius.circular(ScreenUtil().setWidth(49)),
                ),
              ),
              child: Text(
                '添加银行卡',
                style: TextStyle(
                  color: Color(0xffffffff),
                  fontSize: ScreenUtil().setSp(32),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            onTap: () {
              _submitCertificatesInfo();
            },
          ),
          SizedBox(height: ScreenUtil().setWidth(44.0)),
        ],
      ),
    );
  }

  Widget caiTypeView() {
    return Container(
      height: ScreenUtil().setWidth(110),
      padding: EdgeInsets.all(ScreenUtil().setWidth(32)),
      margin: EdgeInsets.only(bottom: ScreenUtil().setWidth(32.0)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '银行卡类型',
            style: TextStyle(
                color: Color(0xff333333),
                fontSize: ScreenUtil().setWidth(30),
                fontWeight: FontWeight.w400),
          ),
          Row(
            children: [
              Image.asset(
                'assets/icon/icon_fill_xuanze.png',
                width: ScreenUtil().setWidth(40),
                height: ScreenUtil().setWidth(40),
              ),
              SizedBox(
                width: ScreenUtil().setWidth(12),
              ),
              Text(
                '储蓄卡',
                style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: ScreenUtil().setWidth(30),
                    fontWeight: FontWeight.w400),
              ),
            ],
          )
        ],
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(
            ScreenUtil().setWidth(32),
          ),
        ),
        color: Color(0xffF6F8FC),
      ),
    );
  }
}

class BackCarCell extends StatelessWidget {
  final String title;
  final String des;
  final Function onChanged;
  final Function click;
  final bool enabled;
  final TextEditingController controller;

  BackCarCell(
      {this.title,
      this.des,
      this.controller,
      this.onChanged,
      this.click,
      this.enabled});

  @override
  Widget build(BuildContext context) {
    Color mycolor = Color(0xffB5B5B5);
    if (des == '请选择银行' ||
        des == '请输入银行卡号' ||
        des == '请输入持卡人' ||
        des == '请输入身份证号' ||
        des == '请输入手机号码') {
      mycolor = Color(0xffB5B5B5);
    } else {
      mycolor = Color(0xff333333);
    }
    return Container(
      alignment: Alignment.center,
      height: ScreenUtil().setWidth(110),
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(32),
          right: enabled != null
              ? ScreenUtil().setWidth(0)
              : ScreenUtil().setWidth(32)),
      margin: EdgeInsets.only(bottom: ScreenUtil().setWidth(32.0)),
      child: InkWell(
        child: TextField(
            textAlign: TextAlign.right,
            style: TextStyle(
                fontSize: ScreenUtil().setSp(32.0), color: Color(0xff333333)),
            //输入文本的样式
            enabled: enabled == null,
            decoration: InputDecoration(
              icon: Container(
                width: title.length > 5
                    ? ScreenUtil().setWidth(230.0)
                    : ScreenUtil().setWidth(160.0),
                child: Text(
                  title,
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(32),
                      color: Color(0xff333333)),
                ),
              ),
              hintText: des,
              hintStyle:
                  TextStyle(fontSize: ScreenUtil().setSp(30.0), color: mycolor),
              border: InputBorder.none,
              suffixIcon: enabled != null
                  ? Icon(
                      Icons.keyboard_arrow_right,
                      color: Color(0xffB5B5B5),
                      size: ScreenUtil().setWidth(40),
                    )
                  : null,
            ),
            onChanged: onChanged,
            controller: controller),
        onTap: click,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(
            ScreenUtil().setWidth(32),
          ),
        ),
        color: Color(0xffF6F8FC),
      ),
    );
  }
}
